package fm.dongman.animefm.view.activity

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import fm.dongman.animefm.R
import org.jetbrains.anko.startActivity
import java.lang.ref.WeakReference

class SplashActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)
        checkPermission()
    }

    /**
     * 检测权限
     */
    private fun checkPermission() {
        // 只有在系统 6.0 之后才申请
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            askingPermission(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE))
        } else {
            onGranted()
        }
    }

    /**
     * 询问权限
     */
    private fun askingPermission(permission: Array<String>) {
        // 检测是否给予过权限
        if (ContextCompat.checkSelfPermission(this, permission[0]) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission[0])) {
                // 用户曾经默认拒绝给予权限
            }
            // 向用户申请权限
            ActivityCompat.requestPermissions(this, permission, PERMISSION_EXTERNAL_STORAGE)
        } else {
            onGranted()
        }
    }

    /**
     * 授予权限后
     */
    private fun onGranted() {
        // 发送延迟启动
        TimeHandler(this).sendEmptyMessageDelayed(0, TIME_DELAYED)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
                                            grantResults: IntArray) {
        when (requestCode) {
            PERMISSION_EXTERNAL_STORAGE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限授予
                    onGranted()
                } else {
                    // 权限拒绝
                    finish()
                }
            }
        }
    }

    /**
     * 定时启动的 Handler
     */
    class TimeHandler constructor(activity: SplashActivity) : Handler() {
        private val mActivity: WeakReference<SplashActivity> = WeakReference(activity)

        override fun handleMessage(msg: Message?) {
            mActivity.get()?.startActivity<IndexActivity>()
            mActivity.get()?.finish()
        }
    }

    companion object {
        private val TIME_DELAYED = 1000L
        private val PERMISSION_EXTERNAL_STORAGE: Int = 0x10
    }
}
